package cn.shyouchi.wuguanjia.android.ui.patrol;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.patrol.PatrolApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.PatrolLineSelEvent;
import cn.shyouchi.wuguanjia.android.impl.ModuleItemClickListener;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.ui.event.checknum.CheckNumLineEntity;
import cn.shyouchi.wuguanjia.android.ui.patrol.begin.BeginPatrolActivity;
import cn.shyouchi.wuguanjia.android.ui.patrol.report.page.PreviewPatrolErrorActivity;
import cn.shyouchi.wuguanjia.android.ui.patrol.statistic.PatrolStatisticActivity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.hintprogressbar.HintProgressBar;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class PatrolActivity extends BaseActivity implements ModuleItemClickListener<PatrolModuleEntity> {


    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.model_name)
    TextView mModelName;
    @BindView(R.id.line_name)
    TextView mLineName;
    @BindView(R.id.person_info_next)
    ImageView mPersonInfoNext;
    @BindView(R.id.sel_line)
    RelativeLayout mSelLine;
    @BindView(R.id.tv_turn_total)
    TextView mTvTurnTotal;
    @BindView(R.id.turn_progress)
    HintProgressBar mTurnProgress;
    @BindView(R.id.tv_turn_complete)
    TextView mTvTurnComplete;
    @BindView(R.id.tv_point_total)
    TextView mTvPointTotal;
    @BindView(R.id.point_progress)
    HintProgressBar mPointProgress;
    @BindView(R.id.tv_point_complete)
    TextView mTvPointComplete;
    @BindView(R.id.rv_patrol_module)
    RecyclerView mRvPatrolModule;


    List<PatrolModuleEntity> mModuleEntities = new ArrayList<>();

    PatrolModuleAdapter mModuleAdapter;

    CheckNumLineEntity.ResultMessageBean mPatrolLine;

    PatrolApi mPatrolApi;

    @Override
    public int initContentView() {
        return R.layout.activity_patrol;
    }

    @Override
    public void initInjector() {
        mPatrolApi = new PatrolApi(mContext);

    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());

        EventBus.getDefault().register(this);

        mModuleEntities.add(new PatrolModuleEntity(BeginPatrolActivity.class, R.mipmap.ic_patrol_module_begin, "开始巡检"));
        mModuleEntities.add(new PatrolModuleEntity(PreviewPatrolErrorActivity.class, R.mipmap.ic_patrol_module_report, "上报信息"));
        mModuleEntities.add(new PatrolModuleEntity(PatrolStatisticActivity.class, R.mipmap.ic_patrol_module_statistic, "巡检统计"));

        mModuleAdapter = new PatrolModuleAdapter(mModuleEntities, this);
        mRvPatrolModule.setLayoutManager(new GridLayoutManager(mContext, 2));
        mRvPatrolModule.setAdapter(mModuleAdapter);

        fetchLine();

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @OnClick({R.id.sel_line})
    public void onClick() {
//        startActivity(new Intent(mContext, SelPatrolLineActivity.class));
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLineSel(PatrolLineSelEvent event) {
        this.mPatrolLine = event.getPatrolLineEntity();
        mLineName.setText(mPatrolLine.getName());
        fetch(event.getPatrolLineEntity());

    }


    @Override
    public void moduleItemClick(PatrolModuleEntity model) {

        if (model.getTarget() == PatrolStatisticActivity.class) {
            mContext.startActivity(new Intent(mContext, model.getTarget()));
            return;
        }

        if (model.getTarget() == PreviewPatrolErrorActivity.class) {
            mContext.startActivity(new Intent(mContext, model.getTarget()));
            return;
        }

        if (mPatrolLine != null ) {
            if (model.getTarget() == BeginPatrolActivity.class) {
                Intent intent = new Intent(mContext, model.getTarget());
                intent.putExtra("line", mPatrolLine);
                mContext.startActivity(intent);
            }
        } else {
            ToastUtil.showToast("请先选择线路");
        }
    }

    @Override
    public void moduleItemLongClick(PatrolModuleEntity model) {

    }

    @Override
    public void onDel(PatrolModuleEntity model) {

    }


    private void fetch(CheckNumLineEntity.ResultMessageBean bean) {
        mPatrolApi.getPatrolRate(String.valueOf(bean.getId()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<PatrolRateEntity>(mContext) {

                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onNext(PatrolRateEntity patrolRateEntity) {
                        mTurnProgress.setProgress(patrolRateEntity.getResultMessage().getTurn());
                        mPointProgress.setProgress(patrolRateEntity.getResultMessage().getNumber());


                        mTvTurnComplete.setText(String.format("圈数：%s/%s", patrolRateEntity.getResultMessage().getTurn_ring(), patrolRateEntity.getResultMessage().getRing()));
                        mTvPointComplete.setText(String.format("点数：%s/%s", patrolRateEntity.getResultMessage().getTurn_actual(), patrolRateEntity.getResultMessage().getTurn_total()));

                    }
                });
    }

    private void fetchLine() {
        mPatrolApi.getPatrolLines()
                .subscribeOn(Schedulers.io())
                .map(new Func1<CheckNumLineEntity, List<CheckNumLineEntity.ResultMessageBean>>() {
                    @Override
                    public List<CheckNumLineEntity.ResultMessageBean> call(CheckNumLineEntity entity) {
                        return entity.getResultMessage();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<CheckNumLineEntity.ResultMessageBean>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        showAlert(e.getMessage());
                    }

                    @Override
                    public void onNext(List<CheckNumLineEntity.ResultMessageBean> resultMessageBeen) {

                        if (!resultMessageBeen.isEmpty()) {
                            EventBus.getDefault().post(new PatrolLineSelEvent(resultMessageBeen.get(0)));
                        } else {
                            showAlert("没有巡检路线");
                        }

                    }
                });
    }


    private void showAlert(String msg) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext, android.app.AlertDialog.THEME_HOLO_LIGHT);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }



}
